package com.asp.alumnisystem.net;

import com.asp.alumnisystem.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 请求manager
 */
public class RetrofitManager {

    private static volatile RetrofitManager retrofitManager;
    private ApiService mApiService;

    public static ApiService getApi(String ip){
        if (retrofitManager == null){
            synchronized (RetrofitManager.class){
                if (retrofitManager == null){
                    retrofitManager = new RetrofitManager(ip);
                }
            }
        }
        return retrofitManager.mApiService;
    }

    public static ApiService getApi(){
        return retrofitManager.mApiService;
    }

    private RetrofitManager(String ip) {
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(ip + Config.WEB_NAME)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mApiService = retrofit.create(ApiService.class);
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS);

        if (BuildConfig.DEBUG){
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
        }

        return builder.build();
    }

}
